package cn.zzf.leetcode;

/**
 * <pre>{@code
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * }</pre>
 * <img width='540' height='221' src='https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg'/>
 * <pre>{@code
 * 示例 1：
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 *
 * 示例 2：
 * 输入：head = [1], n = 1
 * 输出：[]
 *
 * 示例 3：
 * 输入：head = [1,2], n = 1
 * 输出：[1]
 * }</pre>
 * @author zzf
 * @date 2025/6/30
 */
public class T0019_RemoveNthFromEnd {

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode[] tmp = new ListNode[31];
        ListNode current = head;
        int size = 0;
        for (int i = 0; i < tmp.length; i++) {
            if(current != null) {
                tmp[i] = current;
            } else {
                size = i;
                break;
            }
            current = current.next;
        }

        if(n == size) {
            return tmp[1];
        } else if(n == 1) {
            tmp[size - 2].next = null;
        } else {
            tmp[size - n - 1].next = tmp[size - n + 1];
        }
        return head;
    }

    public static void main(String[] args) {
        int[] ints = new int[]{3,4,3,9,2,1,0,5,3,8,7,5,4,9,7,6,5,2,0,2,1,4,9,8,6,6,3,6,4,9};
        System.out.println(removeNthFromEnd(ListNode.of(ints), 26));
    }

}
